package com.jtg.security02.controller;

import com.jtg.security02.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 权限使用注解，admin角色可访问
     *
     * @return
     */
    @GetMapping("/index")
    //@PreAuthorize("hasAuthority('admin')")
    public String index() {
        return "后台首页";
    }

    /**
     * 用户登录
     *
     * @param account  帐号
     * @param password 密码
     * @return
     */
    @GetMapping("/login")
    public UserDetails login(String account, String password) {
        UserDetails user = userService.loadUserByUsername(account);
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return user;
    }
}
